import { createStore } from 'vuex'
import axios from 'axios'  // 取消注释 axios 导入

// 设置 axios 的超时时间
axios.defaults.timeout = 10000; // 设置超时时间为 10 秒

export default createStore({
  state: {
    books: [],
    totalElements: 0,
    currentPage: 0,
    totalPages: 0,
    pageSize: 20
  },
  mutations: {
    SET_BOOKS(state, { content, totalElements, number, totalPages, size }) {
      state.books = content
      state.totalElements = totalElements
      state.currentPage = number
      state.totalPages = totalPages
      state.pageSize = size
    },
    SET_CURRENT_PAGE(state, page) {
      state.currentPage = page
    },
    ADD_BOOK(state, book) {
      state.books.push(book)
    },
    UPDATE_BOOK(state, updatedBook) {
      const index = state.books.findIndex(book => book.id === updatedBook.id)
      if (index !== -1) {
        state.books.splice(index, 1, updatedBook)
      }
    }
  },
  actions: {
    async fetchBooks({ commit }, { page = 0, query = '', size = 20 }) {
      try {
        console.log('Fetching books with params:', { page, query, size })
        const response = await axios.get('/api/books/search', {
          params: {
            keyword: query,
            page,
            size
          }
        })
        console.log('API response:', response.data)
        commit('SET_BOOKS', response.data)
      } catch (error) {
        console.error('Error fetching books:', error)
        throw error
      }
    },
    async addBook({ commit }, bookData) {
      try {
        const response = await axios.post('/api/books', bookData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          withCredentials: true
        })
        console.log('Add book response:', response.data)
        commit('ADD_BOOK', response.data)
        return response.data
      } catch (error) {
        console.error('Error adding book:', error)
        if (error.response) {
          console.error('Error response:', error.response.data)
          console.error('Error status:', error.response.status)
        }
        throw error
      }
    },
    async fetchBook({ commit }, id) {
      try {
        const response = await axios.get(`/api/books/${id}`)  // 添加 /api 前缀
        return response.data
      } catch (error) {
        console.error('Error fetching book:', error)
        throw error  // 抛出错误以便在组件中捕获
      }
    },
    async borrowBook({ commit }, id) {
      try {
        const response = await axios.put(`/api/books/${id}/borrow`)  // 添加 /api 前缀
        commit('UPDATE_BOOK', response.data)
        return response.data
      } catch (error) {
        console.error('Error borrowing book:', error)
        throw error
      }
    },
    async returnBook({ commit }, id) {
      try {
        const response = await axios.put(`/api/books/${id}/return`)  // 添加 /api 前缀
        commit('UPDATE_BOOK', response.data)
        return response.data
      } catch (error) {
        console.error('Error returning book:', error)
        throw error
      }
    },
    async downloadBook({ commit }, id) {
      try {
        const response = await axios.get(`/api/books/${id}/download`, {  // 添加 /api 前缀
          responseType: 'blob'
        })
        return response
      } catch (error) {
        console.error('Error downloading book:', error)
        throw error
      }
    },
    async searchBooks({ commit }, query) {
      try {
        const response = await axios.get(`/books/search?q=${encodeURIComponent(query)}`)
        commit('SET_BOOKS', response.data)
      } catch (error) {
        console.error('Error searching books:', error)
      }
    }
  }
})